package com.javachmapi.springbootemail.config;

import com.javachmapi.springbootemail.dao.SysEmailDao;
import com.javachmapi.springbootemail.entity.SysEmail;
import com.javachmapi.springbootemail.service.impl.SysEmailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * 1、重写邮箱SpringBoot发件人配置类
 * 2、设计实现多账号，轮询发送
 * @EnableConfigurationProperties注解
 * 将MailProperties这个保存邮件相关信息的bean注入到本类引用中
 */
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MyEmailSenderImpl extends JavaMailSenderImpl {

    private final MailProperties properties;

    @Autowired
    private SysEmailDao sysEmailDao;

    public MyEmailSenderImpl(MailProperties properties) {
        this.properties = properties;
    }

    @Override
    protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException {

        try{
            SysEmail sysemail = sysEmailDao.getSysEmailState();
            super.setUsername(sysemail.getUsername()+sysemail.getType());
            super.setPassword(sysemail.getPassword());
            super.setHost(sysemail.getType().replace("@", "smtp."));
            // 设置编码和各种参数
            super.setPort(this.properties.getPort());
            super.setDefaultEncoding(this.properties.getDefaultEncoding().name());
            super.setJavaMailProperties(asProperties(this.properties.getProperties()));
            super.doSend(mimeMessage, object);

        }catch (Exception e){
            e.getMessage();
        }

    }

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }

    @Override
    public String getUsername() {
        return super.getUsername();
    }
}
